package com.shenhaofeng.app.camera;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Administrator on 2016/3/23.
 */
public class CameraController {

    private static final String SAVE_STATUS = "status";


    private Callback callback;

    private List<Callback> interceptCallback = new ArrayList<>();

    private HashMap<Integer, Camera> cameras = new HashMap<>();

    private ArrayList<Integer> albumRequestCodeCache = new ArrayList<>();


    private CameraController(Callback callback) {
        this.callback = callback;
    }


    public static CameraController create(Callback callback) {
        return new CameraController(callback);
    }


    /**
     * 不要手动调用这个方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (cameras.containsKey(requestCode)) {
            Camera camera = cameras.remove(requestCode);
            for (int i = 0; i < interceptCallback.size(); i++) {
                boolean result = interceptCallback.get(i).onCamera(requestCode, resultCode == Activity.RESULT_OK, camera);
                if (result) {
                    return;
                }
            }
            callback.onCamera(requestCode, resultCode == Activity.RESULT_OK, camera);
        } else if (albumRequestCodeCache.contains(requestCode)) {
            albumRequestCodeCache.remove(Integer.valueOf(requestCode));
            for (int i = 0; i < interceptCallback.size(); i++) {
                boolean result = interceptCallback.get(i).onSelectedPhoto(requestCode, resultCode == Activity.RESULT_OK, data == null ? null : data.getData());
                if (result) {
                    return;
                }
            }
            callback.onSelectedPhoto(requestCode, resultCode == Activity.RESULT_OK, data == null ? null : data.getData());
        }
    }


    /**
     * 在Activity或者Fragment的onSaveInstanceState方法中调用
     *
     * @param outState
     */
    public void onSaveInstanceState(Bundle outState) {
        State state = new State(cameras, albumRequestCodeCache);
        outState.putParcelable(SAVE_STATUS, state);
    }


    /**
     * 在Activity或者Fragment的onCreate方法中调用
     *
     * @param savedInstanceState
     */
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(SAVE_STATUS)) {
                State state = savedInstanceState.getParcelable(SAVE_STATUS);
                if (state != null) {
                    this.albumRequestCodeCache.clear();
                    this.cameras.clear();
                    this.albumRequestCodeCache.addAll(state.albumRequestCodeCache);
                    this.cameras.putAll(state.cameras);
                }
            }
        }
    }


    /**
     * 注册回调拦截事件,只有最后注册的回调才会生效
     *
     * @param callback
     */
    public void registerInterceptCallback(Callback callback) {
        if (!interceptCallback.contains(callback)) {
            this.interceptCallback.add(callback);
        }
    }


    /**
     * 移除回调拦截事件
     *
     * @param callback
     */
    public void unregisterInterceptCallback(Callback callback) {
        if (interceptCallback.contains(callback)) {
            this.interceptCallback.remove(callback);
        }
    }


    /**
     * 启动相机
     *
     * @param activity
     * @param option
     * @return
     */
    public Camera openCamera(Activity activity, int request, Option option) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (option == null) {
            Uri outputUri = Option.getDefaultUri(activity, String.valueOf(System.currentTimeMillis()));
            Camera camera = new Camera(outputUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            activity.startActivityForResult(intent, request);
            //保存相机对象
            cameras.put(request, camera);
            return camera;
        }
        Uri outputUri = option.getOutputUri();
        Camera camera = new Camera(outputUri);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        activity.startActivityForResult(intent, request);
        //保存相机对象
        cameras.put(request, camera);
        return camera;
    }


    public Camera openCamera(Fragment fragment, int request, Option option) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (option == null) {
            Uri outputUri = Option.getDefaultUri(fragment.getContext(), String.valueOf(System.currentTimeMillis()));
            Camera camera = new Camera(outputUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            fragment.startActivityForResult(intent, request);
            //保存相机对象
            cameras.put(request, camera);
            return camera;
        }
        Uri outputUri = option.getOutputUri();
        Camera camera = new Camera(outputUri);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        fragment.startActivityForResult(intent, request);
        //保存相机对象
        cameras.put(request, camera);
        return camera;
    }


    /**
     * 打开相册
     *
     * @param activity
     * @param requestCode
     */
    public void openAlbum(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        albumRequestCodeCache.add(requestCode);
        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 打开相册
     *
     * @param fragment
     * @param requestCode
     */
    public void openAlbum(Fragment fragment, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        albumRequestCodeCache.add(requestCode);
        fragment.startActivityForResult(intent, requestCode);
    }


    /**
     * 实现之后可以为CameraController某些情况下能够回调
     */
    public interface Callback {

        boolean onCamera(int request, boolean result, Camera camera);


        boolean onSelectedPhoto(int request, boolean result, Uri uri);

    }



    public static class State implements Parcelable {

        private HashMap<Integer, Camera> cameras = new HashMap<>();

        private ArrayList<Integer> albumRequestCodeCache = new ArrayList<>();


        public State(HashMap<Integer, Camera> cameras, ArrayList<Integer> albumRequestCodeCache) {
            this.cameras = cameras;
            this.albumRequestCodeCache = albumRequestCodeCache;
        }


        @Override
        public int describeContents() {
            return 0;
        }


        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeMap(this.cameras);
            dest.writeList(this.albumRequestCodeCache);
        }


        protected State(Parcel in) {
            this.cameras = (HashMap<Integer, Camera>) in.readSerializable();
            this.albumRequestCodeCache = new ArrayList<Integer>();
            in.readList(this.albumRequestCodeCache, Integer.class.getClassLoader());
        }


        public static final Creator<State> CREATOR = new Creator<State>() {
            @Override
            public State createFromParcel(Parcel source) {
                return new State(source);
            }


            @Override
            public State[] newArray(int size) {
                return new State[size];
            }
        };
    }


}
